package com.study.jdk.j7;

import org.junit.Test;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Scanner;

/**
 * @author: jzhou
 * @date: 2024/11/30-19:54
 * @version: 1.0
 * @description: juc-study
 */
public class NewFeature {

    /**
     * try-with-resources
     */
    @Test
    public void test1() {
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            // 这里可以放置对channel的操作，例如读写文件等
        } catch (Exception e) {
            // 处理异常
        }
        // Multiple Resources 如果要使用多个文件，则可以在try()语句中打开文件，并用分号将它们分开：
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("fileName"));
             Scanner scanner = new Scanner(System.in)) {
            if (scanner.hasNextLine())
                writer.write(scanner.nextLine());
        } catch (IOException e) {
            // handle the exception
        }
    }

    /**
     * Path 和 Paths
     */
    @Test
    public void test2() {
        // 打印程序使用默认路径
        System.out.println(System.getProperty("user.dir")); // E:\Encoding\study\juc-study
        Path source = Paths.get("pox.xml"); // 相对路径 使用 user.dir 环境变量来定位 1.txt
        Path source1 = Paths.get("d:\\1.txt"); // 绝对路径 代表了  d:\1.txt
        Path source2 = Paths.get("d:/1.txt"); // 绝对路径 同样代表了  d:\1.txt
        Path projects = Paths.get("d:\\data", "projects"); // 代表了  d:\data\projects

        // FileSystems.getDefault() 只能获取当前环境的文件系统
        Path path = FileSystems.getDefault().getPath("bin", "sed.sh");
        try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)){
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

        Path path1 = Paths.get("d:\\data\\projects\\a\\..\\b");
        System.out.println(path1);  // d:\data\projects\a\..\b
        System.out.println(path1.normalize()); // 正常化路径 d:\data\projects\b

    }

    /**
     * Files 使用
     */
    @Test
    public void test3() {
        try {
            Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
            // 2.创建一级目录
            Files.createDirectory(path);
            // 1.创建多级目录
            Files.createDirectories(path);

            // 3.复制文件
            Path source = Paths.get("helloword/data.txt");
            Path target = Paths.get("helloword/target.txt");
            Files.copy(source, target);
            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

            // 4.移动文件
            Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);

            // 删除文件  也可以删除目录 删除目录时，目录必须为空   否则会抛异常 DirectoryNotEmptyException
            Files.delete(target);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
